import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {TemplateService} from "../template.service";
import {Observable} from "rxjs/Observable";
import {EditorComponent} from "../../../comm-components/wangeditor/editor.component";
import {AdOssUploadService} from "../../../lib/service/ad-oss-upload.service";
import {GroupService} from "../../group/group.service";
import {NzMessageService} from "ng-zorro-antd";
import {LocalStorageService} from "../../../lib/service/local-storage.service";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {adSystemApiUrl, AliyunOssOutputUrl} from "../../../../config/api";
import {DisplayService} from "../../display/display.service";

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
  providers: [TemplateService, GroupService]
})
export class EditComponent implements OnInit {

  id;
  validateForm: FormGroup;
  loading = false;
  page = 1;
  pageSize = 5;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  _isSpinning = false;
  description;
  fileList = [];
  picList = [];
  f1 = ['templateCover'];
  submitStatus = false;
  ImageChange = false;
  ImageChangeNum = 0;
  self = this;
  picSizeInfo = '图片建议 500px * 400px';


  constructor(
    private fb: FormBuilder,
    private templateService: TemplateService,
    private _message: NzMessageService,
    private router: Router,
    private adOssUploadService: AdOssUploadService,
    private localStorageService: LocalStorageService,
    private route: ActivatedRoute,
    public element: ElementRef
  ) {
    this.validateForm = fb.group({
      template_name: ['', [Validators.required, Validators.maxLength(30)]],
      template_info: [''],
      introduce: ['', [Validators.required]],
      default: [1, [Validators.required]],
      template_pic: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    this.getTemplateInfo(+this.route.snapshot.params['id']);
  }

//返回control
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  getTemplateInfo(id) {
    this.templateService.getTemplateInfo(id).subscribe(res => {
      if (res.code === 200) {
        this.validateForm.controls['template_name'].setValue(res.data.template_name);
        this.validateForm.controls['default'].setValue(res.data.default);
        this.validateForm.controls['introduce'].setValue(res.data.introduce);
        if (res.data.template_pic) {
          this.validateForm.controls['template_pic'].setValue(res.data.template_pic + '?update=' + new Date().getTime());
          this.picList.push({'src': this.aliyunOssOutputUrl + res.data.template_pic + '?update=' + new Date().getTime()});
          this.fileList.push('pic');
        }
      }
    })
  }


  picError = false;//图片是否错误
  fileChange(flag) {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
      this.validateForm.controls['template_pic'].setValue('');
    } else {
      this.picError = false;
      if (flag) {
        this.uploadImg();
      }
    }
  }

  uploadImg() {
    this.fileList.every((val, idx, array) => {
      if (val && val != "pic") {
        console.log(val);
        this.adOssUploadService.getSignature1(`/v1/common/upload`, '/v1/member/goods_extend_template/edit_template', val, this.element.nativeElement.querySelector('form'))
          .subscribe(res => {
              if (res.code === 200) {
                this.validateForm.controls['template_pic'].setValue(res.data[0]);
                this._message.create('success', '上传图片成功');
              }
            }
          );
      }
      return true;
    });
  }


  PostData(event): void {
    // console.log(event);
  }


  goBack() {
    this.router.navigate(['member/template/list']);
  }


  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    this.fileChange(false);

    if (this.validateForm.valid && !this.picError) {
      this.submitStatus = true;
      this.validateForm.controls.default.setValue(this.validateForm.controls.default.value ? 1 : 0);
      this.validateForm.value['id'] = +this.route.snapshot.params['id'];
      this.templateService.addOrEditTemplateInfo(this.validateForm.value).subscribe(res => {
        if (res.code === 200) {
          this._message.create('success', '修改成功');
          this.router.navigate(['member/template/list']);
        } else {
          this._message.create('error', res.message);
          this.submitStatus = false;
        }
      })
    }

  }
}
